<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{

    public function index(Request $request)
    {
        $keyword = $request->keyword;
        $page = $request->query("page", 1);
        $limit = $request->query("limit", 10);
//        分页返回
        $users = User::when($keyword, function ($query) use ($keyword) {
            return $query->where("name", "like", "%{$keyword}%");
        })->paginate($limit, ["*"], "page", $page);
        return $this->success("获取成功", $users);
    }

    public function show(Request $request)
    {
        $id = $request->id;
        $user = User::where("id", "=", $id)->firstOrFail();
        return $this->success("获取成功", $user);
    }

    public function store(StoreUserRequest $request)
    {
        User::create($request->input() + ["password" => bcrypt("123456")]);
        return $this->success("添加成功");
    }

    public function destroy(Request $request, User $user)
    {
        $user->delete();
        return $this->success("删除成功");
    }

    public function update(UpdateUserRequest $request, User $user)
    {
        $depIds = $user->departments()->get()->pluck("id")->toArray();
//        数组长度

//       1、如果为空数组
        if (count($depIds) == 0) {
            $user->update($request->input());
            return $this->success("修改成功");
        }
        if (!in_array($request->department_id, $depIds)) {
            return $this->error("请先解绑部门，再调整部门");
        } else {
            $user->update($request->input());
            return $this->success("修改成功");
        }
    }


    public function current(Request $request)
    {
        $user = Auth::user();
        return new UserResource($user);
    }

    public function resetPassword(Request $request, User $user)
    {
        if (Auth::id() !== 1) {
            return $this->error("您没有权限修改密码");
        } else {
            $user->password = bcrypt("123456");
            $user->save();
            return $this->success("重置成功");
        }
    }

    public function records(Request $request)
    {
        $user = Auth::user();
        return $this->success("获取成功", $user->records);
    }

    public function updatePassword(Request $request)
    {
//        验证密码和确认密码
        $request->validate([
            "password" => ["required", "confirmed", "between:5,20"]
        ], [
            "password.required" => "密码不能为空",
            "password.confirmed" => "两次密码不一致",
            "password.between" => "密码长度必须在5-20位之间"
        ]);
        $user = Auth::user();
        $user->password = bcrypt($request->password);
        $user->save();
        return $this->success("修改成功");
    }
}
